package com.dnjn.mes.biz.controller;

import com.dnjn.mes.biz.domain.MesWorkforceShift;
import com.dnjn.mes.biz.domain.MesWorkforceShiftClocking;
import com.dnjn.mes.biz.domain.MesWorkforceXref;
import com.dnjn.mes.biz.service.IMesWorkforceShiftClockingService;
import com.dnjn.mes.biz.service.IMesWorkforceShiftService;
import com.dnjn.mes.biz.service.IMesWorkforceXrefService;
import com.dnjn.mes.biz.websocket.WebSocketServer;
import com.dnjn.mes.common.core.controller.BaseController;
import com.dnjn.mes.common.core.domain.AjaxResult;
import com.dnjn.mes.common.utils.DateUtils;
import com.dnjn.mes.common.utils.StringUtils;
import com.dnjn.mes.framework.web.service.SysLoginService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameters;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.websocket.EncodeException;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/open/clock")
public class OpenClockController extends BaseController {

    @Autowired
    private IMesWorkforceShiftClockingService workforceShiftClockingService;

    @Autowired
    private IMesWorkforceShiftService shiftService;
    @Autowired
    private SysLoginService loginService;

    @Autowired
    protected IMesWorkforceXrefService workforceXrefService;

    /**
     * 上班打卡：根据用户名密码校验 是否通过，通过就默认新增打卡记录
     *
     * @Param: shift_id, user_id, user_name, password
     */
    /*@Parameters({
            @Parameter(name = "shiftId", description = "shiftId"),
            @Parameter(name = "userId", description = "userId"),
            @Parameter(name = "userName", description = "userName"),
            @Parameter(name = "password", description = "password")
    })*/
    @Operation(summary = "打卡")
    @PostMapping("/checkToWork")
    public AjaxResult checkToWork(@RequestParam(value = "shiftId", required = true) Long shiftId,
                                  @RequestParam(value = "userId", required = true) Long userId,
                                  @RequestParam(value = "userName", required = true) String userName,
                                  @RequestParam(value = "password", required = true) String password,
                                  @RequestHeader(value = "equipmentId") long equipmentId) throws EncodeException {
        Assert.notNull(shiftId, "shiftId不能为空！");
        Assert.notNull(userId, "userId不能为空！");
        Assert.notNull(userName, "userName不能为空！");
        Assert.notNull(password, "password不能为空！");
        MesWorkforceShiftClocking domain = new MesWorkforceShiftClocking().setEquipmentId(equipmentId)
                .setShiftId(shiftId).setUserId(userId).setUserName(userName).setPassword(password);
        if (null == shiftId || null == userId || StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            return error("请检查信息是否填写");
        }
        //判断用户是否在班次关联人员表mes_workforce_xref下
        Long count = workforceXrefService.lambdaQuery().eq(MesWorkforceXref::getUserId, userId).count();
        if (count <= 0) {
            return error("当前用户不在班次关联下");
        }
        //校验用户名密码；成功记录上班打卡时间
        Boolean flag = loginService.checkInUser(userName, password);
        if (flag) {
            String date = DateUtils.getDate();
            //校验是上班还是下班打卡
            MesWorkforceShiftClocking clocking = workforceShiftClockingService.checkClockInOrOut(equipmentId, userId, domain.getShiftId());
            if (null != clocking) {//如果当前天已经存在这个用户打卡信息，且has_clockin有数据，就是下班打卡
                //判断是否上班打卡
                if ("0".equals(clocking.getHasClockin())) {//未上班打卡,更新打卡时间，状态，更新班次记录表，已开始上班打卡
                    clocking.setHasClockin("1");
                    clocking.setClockinDatetime(LocalDateTime.now());
                    workforceShiftClockingService.updateById(clocking);
                    MesWorkforceShift shift = new MesWorkforceShift();
                    shift.setShiftId(shiftId);
                    shift.setHasClockin("1");
                    shiftService.updateById(shift);
                    return success("上班打卡成功！");
                } else {//已上班打卡
                    clocking.setHasClockout("1");
                    clocking.setClockoutDatetime(LocalDateTime.now());
                    workforceShiftClockingService.updateById(clocking);
                    MesWorkforceShift shift = new MesWorkforceShift();
                    shift.setShiftId(shiftId);
                    shift.setHasClockout("1");
                    //查询shift下的用户列表如果都下班成功，返回可以取消上一班次用户列表展示了
                    List<MesWorkforceShiftClocking> list = workforceShiftClockingService.lambdaQuery().eq(MesWorkforceShiftClocking::getShiftId, shiftId).list();
                    //校验用户全部下班打卡
                    Boolean b = checkUserAllWorkOut(list);
                    if (b) {//为true说明，该班次用户已经全部下班打卡完毕，发送消息
                        //socketServer.onMessage(shift, "END");
                        logger.info(shift.toString() + "班次用户已经全部打卡完毕，取消当前班次列表展示了");
                    }
                    shiftService.updateById(shift);
                    return success("下班打卡成功！");
                }
            } else {
                logger.info("用户没查到！！！" + userName + "用户在mes_workforce_xref表，不在班次记录表mes_workforce_shift_clocking中。userId" + userId + "shiftId" + shiftId);
            }

        }
        return error("打卡失败");
    }




    private Boolean checkUserAllWorkOut(List<MesWorkforceShiftClocking> list) {
        Boolean flag = true;
        if (null == list || list.size() == 0) {
            return flag;
        }
        for (MesWorkforceShiftClocking clocking : list) {
            if ("0".equals(clocking.getHasClockout())) {
                flag = false;
            }
        }
        return flag;
    }


    /**
     * 一键下班打卡
     *
     * @Param: shift_id
     */
    @Operation(summary = "一键下班打卡")
    @Parameters({
//            @Parameter(name = "shiftId", description = "shiftId")
    })
    @PostMapping("/checkOutAll")
    public AjaxResult checkOutAll(@RequestParam("shiftId") Long shiftId, @RequestHeader(value = "equipmentId") long equipmentId) throws EncodeException {
        Assert.notNull(shiftId, "shiftId不能为空！");
        workforceShiftClockingService.checkOutAll(shiftId, equipmentId);
        return success("一键下班打卡成功！");
    }

}
